package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.utils.ObjectUtils;
import cn.edu.tju.elm.repository.BusinessRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * ClassName: BussinessService
 * Package: cn.edu.tju.elm.service
 * Description:
 *
 * @Author Niu Wenhang
 * @Create 2025/9/17 8:42
 * @Version 1.0
 */
@Service
@Transactional
public class BusinessService {
    private final BusinessRepository businessRepository;

    public BusinessService(BusinessRepository businessRepository) {
        this.businessRepository = businessRepository;
    }

    public Business addBusiness(Business business) {return businessRepository.save(business);}

    public List<Business> getBusinessesByOwnerId(Long ownerId) {
        return businessRepository.findByBusinessOwnerId(ownerId);
    }

    public Optional<Business> getBusinessById(Long id) {
        return businessRepository.findById(id);
    }
    
    public Optional<Business> getActiveBusinessById(Long id) {
        Optional<Business> businessOpt = businessRepository.findById(id);
        if (businessOpt.isPresent() && businessOpt.get().getDeleted() != null && businessOpt.get().getDeleted()) {
            return Optional.empty();
        }
        return businessOpt;
    }

    public Business updateBusiness(Business business) {
        return businessRepository.save(business);
    }

    public void deleteBusiness(Long id) {
        Optional<Business> businessOpt = businessRepository.findById(id);
        if (businessOpt.isEmpty()) {
            throw new EntityNotFoundException("店铺不存在，ID: " + id);
        }
        Business business = businessOpt.get();
        if (business.getDeleted() != null && business.getDeleted()) {
            throw new EntityNotFoundException("店铺已被删除，ID: " + id);
        }
        business.setDeleted(true);
        business.setUpdateTime(LocalDateTime.now());
        businessRepository.save(business);
    }

    public List<Business> getAllBusinesses() {
        return businessRepository.findByDeletedFalse();
    }

    public List<Business> getBusinessesByNameContaining(String name) {
        return businessRepository.findByBusinessNameContainingAndDeletedFalse(name);
    }

    public List<Business> getBusinessesByAddressContaining(String address) {
        return businessRepository.findByBusinessAddressContainingAndDeletedFalse(address);
    }

    public List<Business> getBusinessesByOrderTypeId(Long orderTypeId) {
        return businessRepository.findByOrderTypeIdAndDeletedFalse(orderTypeId);
    }

    /**
     * 搜索店铺
     * @param name 店铺名称（可选）
     * @param address 店铺地址（可选）
     * @param orderTypeId 订单类型ID（可选）
     * @return 符合条件的店铺列表
     */
    public List<Business> searchBusinesses(String name, String address, Integer orderTypeId) {
        List<Business> businesses = businessRepository.findByDeletedFalse();
        
        // 根据名称过滤
        if (name != null && !name.trim().isEmpty()) {
            businesses = businesses.stream()
                    .filter(business -> business.getBusinessName().toLowerCase().contains(name.toLowerCase()))
                    .collect(java.util.stream.Collectors.toList());
        }
        
        // 根据地址过滤
        if (address != null && !address.trim().isEmpty()) {
            businesses = businesses.stream()
                    .filter(business -> business.getBusinessAddress() != null && 
                            business.getBusinessAddress().toLowerCase().contains(address.toLowerCase()))
                    .collect(java.util.stream.Collectors.toList());
        }
        
        // 根据订单类型过滤
        if (orderTypeId != null) {
            businesses = businesses.stream()
                    .filter(business -> orderTypeId.equals(business.getOrderTypeId()))
                    .collect(java.util.stream.Collectors.toList());
        }
        
        return businesses;
    }
}
